<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Reservation extends Model
{
//    use SoftDeletes;
    protected $guarded = [];

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';

    //预约记录
    function reservation($query){
        $where = [];

        //预约状态
        if($query->reservation_status){
            if($query->reservation_status == 1){//已取消
                $where[] = ['reservation_status',$query->reservation_status];
            }elseif ($query->reservation_status == 2){//正常
                $where[] = ['end','>',date('Y-m-d H:i:s')];
            }elseif($query->reservation_status == 3){//完成
                $where[] = ['end','<',date('Y-m-d H:i:s')];
            }
        }

        //分配状态  1：自动分配；2：手动分配；3：未分配
        if($query->allot_status){
            if($query->allot_status == 3){
                $where[] = ['manager_id',0];
            }else{
                $where[] = ['allot_status',$query->allot_status];
            }
        }

        if($query->company_id){
            $where[] = ['company_id',$query->company_id];
        }
        if($query->username){
            $where[] = ['consumer_infos.username',$query->username];
        }
        if($query->phone){
            $where[] = ['consumer_infos.phone',$query->phone];
        }
        //到访日期
        if($query->start_date){
            $where[] = ['reservation_date','>=',$query->start_date];
        }
        if($query->end_date){
            $where[] = ['reservation_date','<=',$query->end_date];
        }
        //发起时间
        if($query->start_time){
            $where[] = ['create_time','>=',$query->start_time . " H:i:s"];
        }
        if($query->end_time){
            $where[] = ['create_time','<=',$query->end_time . " H:i:s"];
        }

        return $this->select('reservations.*','consumer_infos.username','consumer_infos.phone','consumer_infos.sex','companies.company_name')
                    ->join('consumer_infos','consumer_infos.cid','reservations.cid')
                    ->join('companies','reservations.company_id','companies.id')->where($where)
                    ->orderBy('reservations.create_time')->paginate();

        /*return $this->join('consumer_infos','consumer_infos.cid','reservations.cid')->where($where)
                    ->orderBy('reservations.create_time')->paginate();*/
    }

    //更新预约
    function update_reservation($id,$data){
        return $this->where('id',$id)->update($data);
    }

    //关联用户
    public function user()
    {
        return $this->belongsTo(Consumer::class,'cid');
    }
}

